define(
	[
		'require',
		'./overview_ctrl.js'
	],
	function(require){
		function dateCellFormatter(args, column){
			if (args.row.type & $.wijmo.wijgrid.rowType.data) {
				var data = args.row.data,
					dataKey = column.dataKey,
					formatedTime = APM.util.formatDate(data[dataKey], "yyyy-MM-dd H:mm:ss");
				data["_formatted_"+dataKey] = formatedTime;
				args.$container.append(formatedTime);
				return true;
			}
		}  
		var Controller = Ember.Controller.extend({
			needs: ["businessDetail", "businessCenter","businessOverview"],

			business: Ember.computed.alias('controllers.businessDetail.model'),

			pinTimePoint: Ember.computed.alias('controllers.businessDetail.pinTimePoint'),

			isTradingMode: Ember.computed.alias('controllers.businessDetail.isTradingMode'),

			businessIdChange: Ember.observer("business.id", function(){
				this.set('keyWord', '');
			}),

			initTime: function(){
		        var ctrl = this;
		        var startDate = ctrl.get("startDate");
		        var endDate = ctrl.get("endDate");
		        if(this.get("clickTimePoint") != null ){
		        	var date = new Date(this.get("clickTimePoint"));
		        	ctrl.set("endDate",new Date(+date+60000));
		        	if((isNaN(startDate))){
		        		ctrl.set("startDate",new Date(+date+60000)-60000);
		        	}else{
		        		ctrl.set("startDate",new Date(+date+60000)-(Math.abs(+endDate-(+startDate))));
		        	}
		        	
		        	
		        	setTimeout(function(){
		        		var startDate = APM.util.formatDate(new Date(+ctrl.get("startDate")), "yyyy/MM/dd H:mm");
		        		var endDate = APM.util.formatDate(new Date(+ctrl.get("endDate")), "yyyy/MM/dd H:mm");
		        		$('#config-demo').val(startDate+' - '+endDate);
		        	});
		        	
		        }else{
		        	var sdate = new Date(new Date() - timeD_value - 60000-60000);
			        sdate.setSeconds(0);
			        sdate.setMilliseconds(0); 
			        ctrl.set("startDate",new Date(+sdate));
			        var edate = new Date(new Date() - timeD_value-60000);
			        edate.setSeconds(0);
			        edate.setMilliseconds(0); 
			        ctrl.set("endDate",new Date(+edate));
		        }
		    },

			clickTimePoint: Ember.computed.oneWay('controllers.businessDetail.clickTimePoint'),

			/*timePointLisenterEvent:Ember.computed("clickTimePoint", function(key, value){
				var view = Broada.getView("businessTimeRangesTopo");
				if(this.get("clickTimePoint") != null){
					var date = new Date(this.get("clickTimePoint"));
					if(typeof view != "undefined"){
						var range = view.getTimeRange().endDate - view.getTimeRange().startDate;	
						if(range == 60000){
							this.set("startDate", new Date(date.getTime()-range+60000));
							this.set("endDate", new Date(date.getTime()+60000));
						}else{
							this.set("startDate",new Date(date.getTime()-range+60000));
							this.set("endDate", new Date(date.getTime()+60000));
						}
					}
					typeof view != "undefined"?view.set("btnTxt", date?APM.util.formatDate(date, "f"):null):null;
					this.requireData();
				}
			}),*/

			alarmStartTime: '08:00:00',
			alarmEndTime: '17:00:00',

			//初始化时加载后台告警时间
			initOnloadTime: function(validTime,name){
				var arr = validTime[name].split("-");
				this.set("alarmStartTime",arr[0]);
				this.set("alarmEndTime",arr[1]);
			},

			defaultAlarmTime: function(validTime){
				var ctrl = this;
				ctrl.set("validTimeReturn",validTime);
				for(var name in validTime){
					switch(name){
						case "1":
							$(".alarm-time-day span:eq(0)").addClass("active");
							ctrl.initOnloadTime(validTime,name);
						break;
						case "2":
							$(".alarm-time-day span:eq(1)").addClass("active");
							ctrl.initOnloadTime(validTime,name);
						break;
						case "3":
							$(".alarm-time-day span:eq(2)").addClass("active");
							ctrl.initOnloadTime(validTime,name);
						break;
						case "4":
							$(".alarm-time-day span:eq(3)").addClass("active");
							ctrl.initOnloadTime(validTime,name);
						break;
						case "5":
							$(".alarm-time-day span:eq(4)").addClass("active");
							ctrl.initOnloadTime(validTime,name);
						break;
						case "6":
							$(".alarm-time-day span:eq(5)").addClass("active");
							ctrl.initOnloadTime(validTime,name);
						break;
					}
				};

			},

			alarmTimeChange: Ember.observer("alarmStartTime","alarmEndTime",function(){
				this.set("alarmTimeSlot",this.get("alarmStartTime")+" - "+ this.get("alarmEndTime"));
			}),

			init: function(){
				this.set("alarmTimeSlot",this.get("alarmStartTime")+" - "+ this.get("alarmEndTime"));
			},
			/*
				列配置
			*/
			perfColumns: Ember.computed(function(){
				var columns =  [
				{
					headerText: "交易类型名称",
					dataKey:"name",
					textAlignment:"left",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.name;
							if(data == 0){
								data = 0;
							}else if(!data){
								data = "-";
							}
							var cb = $("<div class='btn-link '></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "交易量",
					dataKey:"throughput",
					textAlignment:"right",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.throughput;
							if(data == 0){
								data = 0;
							}else if(!data){
								data = "-";
							}
							var cb = $("<div></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "平均响应时间",
					dataKey:"responseTime",
					_fmtType: "transform_time",
					textAlignment:"right",
					cellFormatter: APM.util.indicatorCellFormatter
				},
				
				{
					headerText: "成功率",
					dataKey:"successRate",
					textAlignment:"right",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.successRate;
							if(data == 0){
								data = 0;
							}else if(!data){
								data = "-";
							}
							var cb = $("<div></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "错误数",
					dataKey:"error",
					textAlignment:"right",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.performance["business/error/count"];
							if(data == 0){
								data = 0;
							}else if(!data){
								data = "-";
							}
							var cb = $("<div></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				}
			];
			if(!this.get("auth.isNormal")){
					columns.push({
						headerText: "操作",
						dataKey:"id",
						width: 130,
						allowSort: false,
						ensurePxWidth: true,
						cellFormatter: function (args, colume) {
							if (args.row.type & $.wijmo.wijgrid.rowType.data) {
								var ctrl = this.get("controller"),
									data = args.row.data,
									$btnGroup = $('<div class="btn-group"></div>').appendTo(args.$container);

								var ub = $('<button class="btn btn-primary" style="margin-right:4px;" type="button" title="修改交易类型">设置</button>');

								ub.appendTo($btnGroup).on("click",function(){
									ctrl.set("resourceId", data.id);
									var dialog = Broada.getView("set_trade");
									ctrl.requireResourceApdex();
									dialog.openDialog();
								});				

								var ab = $('<button class="btn btn-primary" type="button" title="配置阈值">阈值</button>');
					
								ab.appendTo($btnGroup).on("click",function(){
									var configThresholdsView = Broada.getView("businessConfigThresholdView");
									configThresholdsView.set("targetResource", {targetId: data.id, targetName: data.name+" @"+ctrl.get("model").name});
									configThresholdsView.requireThreshold(data.id);
									configThresholdsView.openDialog();
									ctrl.defaultAlarmTime();
								});

								return true;
							}
						}
					});
				}

				return columns;
			}),

			typeValue: '',

			errorcodes: Ember.A(),

			pageSize: 10,

			transactionType: Ember.A(),

			requireResourceApdex: function() {
				var ctrl = this,
					resourceId = this.get("resourceId");
				return this.store.ajax("GET", "resource/"+resourceId+"/apdex_t", {
					resId : resourceId
				})
				.then(function(response){
					var keyTrade = Ember.A(response['result']);
					ctrl.set("tradeName", keyTrade.name);
					ctrl.set("tradeUri", keyTrade.uri);
					ctrl.set("apdex_t", keyTrade.apdex_t);
					return response;
				});
			},

			keyUpEnent: function(){
				var ctrl = this;
				setTimeout(function(){
					$("#mouseKeyUp").on("keyup",function(event){
						if(event.keyCode == 13){
							ctrl.requireData();
						};
					});
				},0)
				
			},
			
			requireData: function(){
				var ctrl = this,
					serviceId = ctrl.get("model.id"),
					typeValue = ctrl.get("typeValue");

				var params = {
					"appId": this.get("business.id"),
					"serviceId":serviceId,
					"keyWord": this.get("keyWord"),
				    "startDate": +this.get("startDate"),
					"endDate": +this.get("endDate"),
					"transactionType": typeValue,
					"pageIndex": this.get("pageIndex"),
				    "pageSize": this.get("pageSize"),
				    "orderBy": this.get("orderBy"),
					"desc": this.get("desc")
				};

				if( isLocalDebugModel ){
					params = undefined;
				}

				return this.store.ajax("GET", "trades/type", params)
				.then(function(response){
					var result = response.result || [],
						successRate = "business/success/rate",
						responseTime = "business/response_time/avg",
						error = "business/error/count",
						throughput = "business/throughput/total";
						
						result.forEach(function(node){
							if(node.performance[error] == 0){
								node.error = node.performance[error];
							}else if(!node.performance[error]){
								node.error = node.performance[error];
							}
							if(node.performance[responseTime] == 0){
								node.responseTime = node.performance[responseTime];
							}else if(node.performance[responseTime]){
								node.responseTime = node.performance[responseTime];
							}
							if(node.performance[throughput] == 0){
								node.throughput = node.performance[throughput];
							}else if(node.performance[throughput]){
								node.throughput = node.performance[throughput];
							}
							if(node.performance[successRate] == 0){
								node.successRate = 0+"%";
							}else if(!node.performance[successRate]){
								node.successRate = "-";
							}else{
								node.successRate = node.performance[successRate]+"%";
							}
						});

					if (result.length == 0) {
						ctrl.set("pageIndex",0);
						ctrl.set("pageSize",10);
						ctrl.set("totalRows",0);//设置为0显示没有数据
					} else {
						ctrl.set("pageIndex",response.meta.pageIndex);
						ctrl.set("pageSize",response.meta.pageSize);
						ctrl.set("totalRows",response.meta.total);
					}
					
					ctrl.set("errorcodes",result);
				
					return response;
				});
			},

			actions: {
				search: function() {
					this.set("pageIndex", 0);
					this.requireData();
				},
				addThreshold: function(){
					var ctrl = this,
						configThresholdView = Broada.getView("businessConfigThresholdView");
					this.set("curEditeThreshold", null);
					configThresholdView.newThresholdForm().openDialog();
				},

				gridSorted: function(e, data, view){
					view.ensureControl(false);
					var dataKey = data.column.dataKey;
					switch(dataKey){
						case "responseTime":
						dataKey = "business/response_time/avg";
						break;
						case "error":
						dataKey = "business/error/count";
						break;
						case "throughput":
						dataKey = "business/throughput/total";
						break;
						case "successRate":
						dataKey = "business/success/rate";
						break;
						default:
						return;
						break;
					}
					this.set("orderBy", dataKey);
					this.set("desc", data.sortDirection=="descending"||undefined);
					this.requireData();
				},

				pageIndexChanged: function(e, data, view){
					var pageNo = data.newPageIndex;
					this.set("pageIndex", pageNo);
					this.requireData();
				},

				gridCellClicked: function(e, args, view){
					var ctrl = this,
						row = args.cell.row(),
						column = args.cell.column();
					if (row && (row.type & $.wijmo.wijgrid.rowType.data)) {
						if(column.dataKey == "name"){
							ctrl.set("typeServerId",row.data.performance.serviceId);
							ctrl.transitionToRoute("business.detail.nodetype",ctrl.get("business"),row.data.id);
						}
					}
				},
				scvDownload: function(){
					var ctrl = this,
						serviceId = this.get('model.id'),
						appId = this.get('business.id'),
						menuId = this.get('model.id'),
						startDate = +ctrl.get("startDate"),
						endDate = +ctrl.get("endDate");
						
					confirmDialog("确定要导出交易类型的表格吗？")
					.then(function(){
						var url="/front/rest/apm/trades/downloadTransaction?appId="+appId+"&menuId="+49+"&serviceId="+serviceId+"&name=transactionType&startDate="+startDate+"&endDate="+endDate+"&token="+encodeURIComponent($.cookie("token"));
						window.location.href =url;
					});
				},
				setTrade: function(){
					var ctrl = this;

					var resourceId = this.get("resourceId");
					var name = this.get("tradeUri");
					if(!name){
						this.set("formTip", "交易名称不能为空!");
						return;
					}

					var apdex_t = this.get("apdex_t");
					if (apdex_t && !/^[\d]+$|^\d*\.\d+$/.test(apdex_t)) {
						this.set("formTip", "apdex_t值必须为整数或小数！");
						return;
					}
					
					this.set("formTip", null);
					
					this.store.ajax("PUT", "resource",{
						"resourceId" : resourceId,
						"name" : name,
						"apdex_t" : apdex_t
					}).then(function(response){
						if(response) {
							alertTip("保存成功！", "success");
							ctrl._actions.closeDialog();

							ctrl.requirePerformances();

							ctrl.requireData();
							
							ctrl.set("tradeName","");
							ctrl.set("tradeUri", "");
							ctrl.set("apdex_t","");
						} else {
							alertTip("保存失败！", "error");
						}
					});
				},

				closeDialog: function(){
					Broada.getView("set_trade").closeDialog();
				},

				timePointChange: function(timeRange){
					this.set("startDate",timeRange.startDate);
					this.set("endDate",timeRange.endDate);
			
					this.requireData();
				},

				timeRangesChange: function(timeRange){

					// var ctrl = this,
					// 	locationStart = this.get("locationStart");
					// var isSelectedTime = ctrl.get("controllers.businessDetail").isSelectedTime,
					// 	pinTimePoint = ctrl.get("controllers.businessDetail").pinTimePoint;
					
					// if(!isSelectedTime){
					// 	ctrl.set("startDate", timeRange.startDate);
					// 	ctrl.set("endDate", timeRange.endDate);
					// }else{
					// 	var view = Broada.getView("businessTimeRangesTopo");
					// 	if(this.get("clickTimePoint") != null){
					// 		this.set("locationStart",true);
					// 		var date = new Date(this.get("clickTimePoint"));
					// 		if(typeof view != "undefined"){
					// 			var range = view.getTimeRange().endDate - view.getTimeRange().startDate;	
					// 			if(range == 60000){
					// 				this.set("startDate", new Date(date.getTime()-range+60000));
					// 				this.set("endDate", new Date(date.getTime()+60000));
					// 			}else{
					// 				this.set("startDate",new Date(date.getTime()-range+60000));
					// 				this.set("endDate", new Date(date.getTime()+60000));
					// 			}
					// 		}

					// 		if(ctrl.get("pinTimePoint") != (+view.get("selectedDate"))){
					// 			ctrl.set("pinTimePoint", null);
					// 		}
					// 		this.requireData();
					// 	}
					// };

					// if(timeRange.selectVal == "n1M"||timeRange.selectVal == "n1d"){
					// 	ctrl.set("startDate", timeRange.startDate);
					// 	ctrl.set("endDate", timeRange.endDate);
					// };

					// ctrl.set("pageIndex", 0);
					// ctrl.requireData();


					var ctrl = this;
					var pinTimePoint = ctrl.get("controllers.businessDetail").pinTimePoint;

						ctrl.set("startDate", timeRange.startDate);
						ctrl.set("endDate", timeRange.endDate);
			
					
					var view = Broada.getView("businessTimeRangesTopo");
					if(ctrl.get("pinTimePoint") != timeRange.startDate){
						ctrl.set("pinTimePoint", null);
					}

					/*if(timeRange.selectVal == "n1M"||timeRange.selectVal == "n1d"){
						ctrl.set("startDate", timeRange.startDate);
						ctrl.set("endDate", timeRange.endDate);
					};*/

					ctrl.set("pageIndex", 0);
					ctrl.requireData();
				}
			}
		});

		APM.BusinessDetailNodedetailTypeController = Controller;
		return Controller;
	}
);